package com.webListener;

/**
 * @author Mathison
 * @Title: LoginListener
 * @Package: com.webListener
 * @Description: TODO
 * @date 2021/11/20 14:35
 **/

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


public class LoginListener implements HttpSessionListener,ServletContextListener{
    private ServletContext application = null;
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("context destory");
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("context init");
        application = sce.getServletContext();
        Set<String> onlineUserSet = new HashSet<String>();
        Map userStatusMap = new HashMap();
        application.setAttribute("onlineUserSet", onlineUserSet);
        application.setAttribute("userStatusMap",userStatusMap);
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {

        System.out.println("session create");
    }


//    退出登录时从application的onlineUserSet中删除该用户
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        Set<String> onlineUserSet = (Set<String>)application.getAttribute("onlineUserSet");
        Map userStatusMap = (Map)application.getAttribute("userStatusMap");
        String username = (String)session.getAttribute("username");
        userStatusMap.replace(username,1);
        onlineUserSet.remove(username);
        application.setAttribute("onlineUserSet", onlineUserSet);
        onlineUserSet = (Set<String>)application.getAttribute("onlineUserSet");
//        System.out.println(onlineUserSet.toString());
        System.out.println(username + "超时退出");
        System.out.println("session destory");
    }

}

